package com.yijian.oj.judge.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yijian.oj.common.ErrorCode;
import com.yijian.oj.exception.BusinessException;
import com.yijian.oj.judge.codesandbox.CodeSandBox;
import com.yijian.oj.judge.codesandbox.model.ExecuteCodeRequest;
import com.yijian.oj.judge.codesandbox.model.ExecuteCodeResponse;

import java.util.HashMap;
import java.util.Map;

/**
 * 远程代码沙箱
 * @author ItJianGe
 * @data 2024/3/25 8:11
 */
public class RemoteCodeSandBox implements CodeSandBox {
    public static final String accessKey = "yijian";
    public static final String secretKey = "jiange";
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest codeRequest) {
        String url = "http://localhost:9080/api/execute_code";
        String codeRequestStr = JSONUtil.toJsonStr(codeRequest);
        String executeCodeResponse = HttpUtil.createPost(url)
                .addHeaders(getSign())
                .body(codeRequestStr)
                .execute()
                .body();
        if (StrUtil.isBlankIfStr(executeCodeResponse)) {
            throw new BusinessException(ErrorCode.PORT_OPERATION_ERROR, "远程代码沙箱执行失败");
        }
        return JSONUtil.toBean(executeCodeResponse, ExecuteCodeResponse.class);
    }

    private Map<String, String> getSign() {
        String key = SecureUtil.md5(secretKey);
        Map<String, String> map = new HashMap<>();
        map.put("accessKey", accessKey);
        map.put("secretKey", key);
        return map;
    }
}
